/*
 * @Author: hongbin
 * @Date: 2022-09-04 11:46:18
 * @LastEditors: hongbin
 * @LastEditTime: 2022-09-15 18:32:36
 * @Description:web worker 中做的工作
 */
import THREE from "../index";
import { DRACOLoader } from "three/examples/jsm/loaders/DRACOLoader";
import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js";
import { manager } from "./helper/manager";
import { genAnimations, genGroupStruct } from "./helper/parseModel";
import { undergroundsCheck } from "./helper/undergroundCheck";
// import acter from "../../assets/model/acter.glb";
// import plain from "../../assets/model/plain.glb";
// import grove from "../../assets/model/grove.glb";
// import treasureChest from "../../assets/model/treasureChest.glb";

const dracoLoader = new DRACOLoader(manager);
dracoLoader.setDecoderConfig({ type: "js" });
dracoLoader.setDecoderPath("https://api.hongbin.xyz:3002/kmyc/");
const gltfLoader = new GLTFLoader(manager);
gltfLoader.setDRACOLoader(dracoLoader);

let prevTime = 0;
let isFallIntoFloor = false;

function calculate(e: any) {
    const data = e.data;
    const time = performance.now();
    const intensity = Math.abs(Math.sin(time / 30000));
    //按需计算
    if (e.data.isNeedCalculateUnderground) {
        // isFallIntoFloor = undergroundsCheck(data.currentPlanetName, data.acterBox);
        isFallIntoFloor = undergroundsCheck(data.currentPlanetName, data.acterPosition);
    } else isFallIntoFloor = false;
    prevTime = time;

    postMessage({ work_type: "calculate", intensity, isFallIntoFloor });
}

function modelLoad(modelName: string) {
    gltfLoader.load(
        `/api/glb?name=${modelName}`,
        (gltf) => {
            return postMessage({
                modelName,
                work_type: "parseModel",
                ...genGroupStruct(gltf.scene),
                sceneAnimations: genAnimations(gltf.animations),
            });
        },
        undefined,
        () => {
            postMessage({ msg: "Worker 模型加载错误！" + modelName });
        }
    );
}

// modelLoad(acter, "acter");
// modelLoad(plain, "plain");
// modelLoad(grove, "grove");
// modelLoad(treasureChest, "treasureChest");

/**
 * 监听主线程发来的数信息
 */
onmessage = function (e) {
    switch (e.data.work_type) {
        case "test_connect":
            postMessage({
                msg: "连接成功",
                THREE: new THREE.Vector3(),
            });
            break;
        case "start":
            postMessage({
                msg: "初始化",
                work_type: "log",
                undergroundParams: e.data.undergroundParams,
            });
            undergroundsCheck.update(e.data.undergroundParams);
            break;
        case "calculate":
            calculate(e);
            break;
        case "modelParse":
            modelLoad(e.data.name);
            break;
    }
};

export {};
